package com.example;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Arrays;

public class BufferTest {
    @Test
    public void test1() {
        float vertices[] = {
                -1.0f, 1.0f, 0.0f,  // 0, Top Left
                -1.0f, -1.0f, 0.0f,  // 1, Bottom Left
                1.0f, -1.0f, 0.0f,  // 2, Bottom Right
                1.0f, 1.0f, 0.0f,  // 3, Top Right
        };

        //为了提高性能，通常将这些数组存放到java.io 中定义的Buffer类中：

        // a float is 4 bytes, therefore we multiply the
        //number if vertices with 4.
        ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
        vbb.order(ByteOrder.nativeOrder());
        FloatBuffer vertexBuffer = vbb.asFloatBuffer();
        vertexBuffer.put(vertices);
        vertexBuffer.position(0);

        System.out.println(vertexBuffer.position());
        System.out.println(vertexBuffer.get(0));
    }

    /**
     *
     * @throws JSONException
     */
    @Test
    public void test2() throws JSONException {
        String json = "{\"1\":{\"a\":\"a1\",\"b\":\"b1\"},\"2\":[{\"a\":\"c1\",\"b\":\"d1\"},{\"a\":\"c2\",\"b\":\"d2\"},{\"a\":\"c3\",\"b\":\"d3\"}]}";
        JSONObject object = new JSONObject(json);
        // 得到数组[{"a":"c1","b":"d1"},{"a":"c2","b":"d2"},{"a":"c3","b":"d3"}]
        ArrayList<String> list = new ArrayList<String>();
        JSONArray jsonArray = object.getJSONArray("2");
        //遍历数组, 抽取元素
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if(jsonObject.has("b")){
                String b = jsonObject.getString("b");
                list.add(b);
            }
        }

        // List -> Array
        String[] array = list.toArray(new String[]{});

        System.out.println(Arrays.toString(array));//[d1, d2, d3]
    }
}
